//
//  MXCollocaSingleItemDetailVC.m
//  MXの衣柜
//
//  Created by 马霄 on 15/8/12.
//  Copyright (c) 2015年 霄 马. All rights reserved.
// 搭配商品详情
#define WIDTH ([UIScreen mainScreen].bounds.size.width)
#define HEIGHT ([UIScreen mainScreen].bounds.size.height)

#import "MXCollocaSingleItemDetailVC.h"
#import "AFNetworkHandler.h"
#import "MXHomeItemDetailTopView.h"
#import "MXHomeItemDetailTableViewCell.h"
#import "MXHomeItemDetailModel.h"
#import "MXHomeWebViewVC.h"
#import "DataBaseFMDB.h"
#import <ShareSDK/ShareSDK.h>
@interface MXCollocaSingleItemDetailVC ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) MXHomeItemDetailTopView *topView;
@property (nonatomic, retain) UIButton *backButton;

@property (nonatomic, retain) UIButton *collectButton;

@property (nonatomic, retain) UILabel *TmallLabel;

@property (nonatomic, retain) NSMutableArray *ItemArray;

@property (nonatomic, retain) NSString *TmallLinkString;

@property (nonatomic, retain) NSString *TempTitleString;

@property (nonatomic, retain) NSString *tempPrice;

@property (nonatomic, retain) NSString *imagePath;

@property (nonatomic, retain) NSString *tempUrl;

@property (nonatomic, retain) UIButton *itemCollectButton;

@property (nonatomic, retain) NSString *tempSize;
@end

@implementation MXCollocaSingleItemDetailVC
- (void)dealloc
{
    [_tempSize release];
    [_itemCollectButton release];
    [_tempUrl release];
    [_imagePath release];
    [_tempPrice release];
    [_TempTitleString release];
    [_TmallLinkString release];
    [_ItemArray release];
    [_backButton release];
    [_collectButton release];
    [_topView release];
    [_tableView release];
    [_singleItemDetailID release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    //全局数组初始化
    self.ItemArray = [NSMutableArray array];
    
    [self getData];
    
//    [self creatTableView];
    // Do any additional setup after loading the view.
}

- (void)creatTableView
{
    self.tableView = [[[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - HEIGHTPRO * 49)] autorelease];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    
    if (self.tempSize.length > 0) {
        self.topView = [[[MXHomeItemDetailTopView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHTPRO * 590)] autorelease];
        
    } else {
        self.topView = [[[MXHomeItemDetailTopView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHTPRO * 545)] autorelease];
    }
    
    
    self.topView.backgroundColor = [UIColor grayColor];
    
    self.tableView.tableHeaderView = self.topView;
    self.tableView.userInteractionEnabled = YES;
    [self.view addSubview:self.tableView];
    
}
//// 创建Buttons
- (void)creatButtons
{
    //后退按钮
    self.backButton  = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.backButton.frame = CGRectMake(WIDTHPRO * 20, HEIGHTPRO * 30, WIDTHPRO * 40, HEIGHTPRO * 40);
    self.backButton.layer.cornerRadius = WIDTHPRO * 20;
    self.backButton.backgroundColor = [UIColor blackColor];
    self.backButton.alpha = 0.75;
    [self.backButton setBackgroundImage:[UIImage imageNamed:@"backButton"] forState:(UIControlStateNormal)];
    self.backButton.layer.masksToBounds = YES;
    [self.view addSubview:self.backButton];
    [self.backButton addTarget:self action:@selector(backAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    //收藏按钮
    self.collectButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.collectButton.frame = CGRectMake(WIDTH - WIDTHPRO * 60, HEIGHTPRO * 30, WIDTHPRO * 40,HEIGHTPRO * 40);
    self.collectButton.layer.cornerRadius = WIDTHPRO * 20;
    self.collectButton.backgroundColor = [UIColor blackColor];
    self.collectButton.alpha = 0.75;
    [self.collectButton setBackgroundImage:[UIImage imageNamed:@"shareButton"] forState:(UIControlStateNormal)];
    self.collectButton.layer.masksToBounds = YES;
    [self.view addSubview:self.collectButton];
    [self.collectButton addTarget:self action:@selector(collectAction) forControlEvents:(UIControlEventTouchUpInside)];
    
}
- (void)creatTmallLinkButton
{
    self.TmallLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, HEIGHT - HEIGHTPRO * 49, WIDTH, HEIGHTPRO * 49)];
    self.TmallLabel.backgroundColor = [UIColor whiteColor];
    self.TmallLabel.text = @"";
    self.TmallLabel.layer.borderWidth = 1;
    self.TmallLabel.userInteractionEnabled = YES;
    [self.view addSubview:self.TmallLabel];
    [_TmallLabel release];
    
    UIButton *buyButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    buyButton.backgroundColor = [UIColor redColor];
    buyButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [buyButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [buyButton setTitle:@"天猫购买" forState:(UIControlStateNormal)];
    buyButton.frame = CGRectMake(WIDTH - WIDTHPRO * 120, 0, WIDTHPRO * 80, HEIGHTPRO * 49);
    [buyButton addTarget:self action:@selector(buyAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.TmallLabel addSubview:buyButton];
    
    self.itemCollectButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.itemCollectButton setBackgroundImage:[UIImage imageNamed:@"uncollect"] forState:(UIControlStateNormal)];
    [self.itemCollectButton setBackgroundImage:[UIImage imageNamed:@"collected"] forState:(UIControlStateSelected)];
    self.itemCollectButton.frame = CGRectMake(WIDTHPRO * 20, HEIGHTPRO * 4.5, WIDTHPRO * 40, HEIGHTPRO * 40);
    [self.itemCollectButton addTarget:self action:@selector(itemCollectAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.TmallLabel addSubview:self.itemCollectButton];
    
    
    DataBaseFMDB *dbManger = [[[DataBaseFMDB alloc] init] autorelease];
    
    // 创建数据库
    [dbManger createItemDataBase];
    
    // 创建表
    [dbManger creatItemDaseTable];
    
    BOOL exists = [dbManger isItemExists:self.TempTitleString];
    
    if (exists) {
        self.itemCollectButton.selected = YES;
    }
    
    // 隐藏TabBar
    self.tabBarController.tabBar.hidden = NO;
    
}


- (void)getData
{
    NSString *path = [NSString stringWithFormat:@"http://api.nanyibang.com/items?age=23&height=175&hkm_sign=8ad5187a2a6373a235fc525b898d4e16&item_id=%@&member_id=15243&member_type=member&random_key=3154&skin_type=3&style=1&version=1.2.7&weight=76", self.singleItemDetailID];
//    NSLog(@"%@", path);
    [AFNetworkHandler GETwithAFNByURL:path completion:^(id result) {
//        NSLog(@"%@", result);
        NSDictionary *dataDict = [result objectForKey:@"data"];
        MXHomeItemDetailModel *model = [[[MXHomeItemDetailModel alloc] initWithDic:dataDict] autorelease];
        [self.ItemArray addObject:model];
        
        self.TempTitleString = model.title;
        self.tempPrice = model.coupon_price;
        self.imagePath = model.pic_url;
        self.tempUrl = model.purchaseLink;
        self.tempSize = model.size;
        
        
        [self creatTableView];
        [self creatButtons];
        [self creatTmallLinkButton];
    }];
    
}

//******************************* TableView Delegate 协议实现方法 ***************************
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.ItemArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MXHomeItemDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (!cell) {
        cell = [[MXHomeItemDetailTableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:@"reuse"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [self.topView GetInfo:self.ItemArray[indexPath.row]];
    self.TmallLinkString = [self.ItemArray[indexPath.row] purchaseLink];
    [cell GetInfo:self.ItemArray[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return HEIGHTPRO * 360;
}

#pragma mark - TableView点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
    }
}
//******************************* 按钮点击方法 ***************************
- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)collectAction
{
    
    //创建弹出菜单容器
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    NSArray* imageArray = @[[UIImage imageNamed:@"shareImage"]];
    
    if (imageArray) {
        
        [shareParams SSDKSetupShareParamsByText:@"分享内容"
                                         images:imageArray
                                            url:[NSURL URLWithString:@"http://mob.com"]
                                          title:@"分享标题"
                                           type:SSDKContentTypeImage];
        
        //进行分享
        [ShareSDK share:SSDKPlatformTypeSinaWeibo
             parameters:shareParams
         onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
             
             //             [theController showLoadingView:NO];
             //             [theController.tableView reloadData];
             
             switch (state) {
                 case SSDKResponseStateSuccess:
                 {
                     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                         message:nil
                                                                        delegate:nil
                                                               cancelButtonTitle:@"确定"
                                                               otherButtonTitles:nil];
                     [alertView show];
                     break;
                 }
                 case SSDKResponseStateFail:
                 {
                     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                         message:[NSString stringWithFormat:@"%@", error]
                                                                        delegate:nil
                                                               cancelButtonTitle:@"确定"
                                                               otherButtonTitles:nil];
                     [alertView show];
                     break;
                 }
                 case SSDKResponseStateCancel:
                 {
                     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享已取消"
                                                                         message:nil
                                                                        delegate:nil
                                                               cancelButtonTitle:@"确定"
                                                               otherButtonTitles:nil];
                     [alertView show];
                     break;
                 }
                 default:
                     break;
             }
             
         }];
    }

    
    
    
}
- (void)buyAction
{
    MXHomeWebViewVC *webViewVC = [[[MXHomeWebViewVC alloc] init] autorelease];
    webViewVC.requestString = self.TmallLinkString;
    [self presentViewController:webViewVC animated:YES completion:^{
        
    }];
}

- (void)itemCollectAction:(UIButton *)collectButton
{
    
    DataBaseFMDB *dbManger = [[[DataBaseFMDB alloc] init] autorelease];
    
    // 创建数据库
    [dbManger createItemDataBase];
    
    // 创建表
    [dbManger creatItemDaseTable];
    
    collectButton.selected = !collectButton.selected;
    
    BOOL exists = [dbManger isItemExists:self.TempTitleString];
    
    
    if (collectButton.selected == YES) {
        [dbManger insertItemTable:self.TempTitleString ItemID:self.tempUrl imagePath:self.imagePath Price:self.tempPrice];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"收藏成功!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
        [alert show];
        [alert release];
        
    } else if (exists){
        //        collectButton.selected = YES;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"取消收藏" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
        [alert show];
        [alert release];
        
        [dbManger deleteItemData:self.TempTitleString];
        
    }

    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
